package com.itzmn.newcode.offer;

import java.awt.datatransfer.Transferable;

/**
 * @Author: 张梦楠
 * @Date: 2018/11/23 15:09
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 剑指Offer  将字符串转成整数
 *
 *  思路：判断是否是规范的
 *  是否包含不是数字
 *
 */
public class StringToInteger {


    public static void main(String[] args) {

        new StringToInteger().StrToInt("12345");
    }


    public int StrToInt(String str) {

        char[] chars = str.toCharArray();

        if (str.length()==0 || str == null){
            return 0;
        }
        int flag = 0;

        int fuhao = 0;

        if ('-' == chars[0]){
            fuhao = 1;
            flag = 1;
        }else if ('+' == chars[0]){
            fuhao = 2;
            flag = 1;
        }else if(chars[0] >57 || chars[0]<48){
            return 0;
        }

        int sum = 0;
        for (int i=flag;i<chars.length;i++){

            if (chars[i] <=57 && chars[i]>=48){
                sum = sum * 10 + chars[i]-48;
            }else {
                return 0;
            }
        }

        sum = fuhao==1? sum*-1:sum;
        System.out.println(sum);
        return sum;

    }



}
